<template>
	<view class="work-experience-page">
		<!-- <nav-header title="工作经历"></nav-header> -->

		<view class="content" style="background-color: #fff;">
			<view class="page-title">{{ pageTitle }}</view>
			<view class="subtitle">填写你的工作经历</view>
			<!-- Edit Form Popup -->
			<view class="form-container">
				<!-- companyName Field -->
				<view class="form-item">
					<text class="form-label required">公司名称</text>
					<input class="form-input" type="text" v-model="formData.companyName" placeholder="请输入公司名称" />
				</view>

				<!-- job Field -->
				<view class="form-item">
					<text class="form-label required">职位名称</text>
					<input class="form-input" type="text" v-model="formData.job" placeholder="请输入职位名称" />
				</view>

				<!-- Work Time -->
				<view class="form-item">
					<text class="form-label required">工作时间</text>
					<view class="time-range">
						<!-- Start Time -->
						<picker mode="date" :value="formatTimeForPicker(formData.startDate)" fields="month"
							@change="handleStartTimeChange">
							<view class="time-picker">
								<text>{{ formData.startDate ? formatTime(formData.startDate) : '开始时间' }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>

						<text class="time-separator">至</text>

						<!-- End Time -->
						<picker mode="date" :value="formatTimeForPicker(formData.endDate)" fields="month"
							@change="handleEndTimeChange">
							<view class="time-picker">
								<text>{{ formData.endDate ? formatTime(formData.endDate) : '至今' }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>
				</view>

				<!-- jobDescription Field -->
				<view class="form-item">
					<view class=""
						style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 10px;">
						<text class="form-label">工作内容</text>
						<button class="generate-btn" @click="generateWork">
							<text class="generate-icon">✨</text>
							AI生成
						</button>
					</view>
					<textarea class="form-textarea" v-model="formData.jobDescription" placeholder="描述你的工作职责、成果和贡献等"
						maxlength="1000"></textarea>
					<text class="word-count">{{ formData.jobDescription ? formData.jobDescription.length : 0 }}/1000</text>
				</view>

				<view class="bottom">
					<!-- Delete Button -->
					<view class="delete-action" v-if="!isAdding">
						<button class="delete-btn" @click="confirmDelete">删除</button>
					</view>
					<!-- Save Button -->
					<view class="action-bar">
						<button class="save-btn" @click="saveWork">保存</button>
					</view>
				</view>
			</view>
			<view>
				<!-- 普通弹窗 -->
				<uni-popup ref="popupWork" background-color="#fff" mask-background-color="rgba(0,0,0,0)"
					:is-mask-click="false" type="bottom" borderRadius='20px 20px 0 0 '>
					<view class="popup-content">
						<view class="popup-header">
							<text class="popup-title">AI生成</text>
							<uni-icons type="closeempty" size="24" @click="closePopupWork"></uni-icons>
						</view>
						<view class="popup-body">
							<text>{{ experienceType == 'internExperiences' ? AIContentInternship : AIContent }}</text>
						</view>
						<view class="popup-footer">
							<button class="popup-btn" @click="rewriteWork">重写</button>
							<button type="primary" class="popup-btn" @click="replaceWork">替换</button>
						</view>
					</view>
				</uni-popup>
			</view>

			<!-- Delete Confirmation -->
			<uni-popup ref="deletePopup" type="dialog">
				<uni-popup-dialog title="删除确认" content="确定要删除这条工作经历吗？删除后将无法恢复。" :beforeClose="true"
					@confirm="deleteWork" @close="closeDeletePopup"></uni-popup-dialog>
			</uni-popup>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		nextTick
	} from 'vue'
	import NavHeader from '@/components/nav-header.vue'
	import ExperienceItem from '@/components/experience-item.vue'
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app'
	import {
		useResumeStore
	} from '@/store/resume.js'
	import {
		getWorkExperienceList,
		getWorkExperienceDetail,
		addWorkExperience,
		updateWorkExperience,
		deleteWorkExperience,
		generateWorkExperienceDescription,
		getInternshipExperienceList,
		getInternshipExperienceDetail,
		addInternshipExperience,
		updateInternshipExperience,
		deleteInternshipExperience,
		generateInternshipExperienceDescription
	} from '@/api/edit/work.js'
	import {
		formatToFirstDay
	} from '@/utils/format.js'
	import env from '@/env'
	import { useAuthStore } from '@/store/index';
	import { mockInterviewWebSocketProcess } from '@/api/ai'
	import { useWebSocket } from '@/utils/useWebSocket'
	
	const authStore = useAuthStore();
	const statusBarHeight = ref(20)
	const formPopup = ref(null)
	const deletePopup = ref(null)
	const isAdding = ref(true)
	const currentIndex = ref(-1)
	const currentId = ref(null)
	const experienceType = ref('workExperiences') // 'work' or 'intern'
	const pageTitle = ref('工作经历')
	const formData = reactive({
		companyName: '',
		job: '',
		startDate: '',
		endDate: '',
		jobDescription: '',
		resumeId: ''
	})
	const workList = ref([])
	const resumeStore = useResumeStore()
	const AIContent = ref('')
	const AIContentInternship = ref('')
	const popupWork = ref(null)
	const isGenerating = ref(false)
	const { messages, isConnected, connect, sendMessage, close, onMessage } = useWebSocket(env.websocket)

	// 注册WebSocket消息处理函数
	onMessage((data) => {
		uni.hideLoading();
		try {
			if (typeof data === 'string') {
				try {
					const parsedData = JSON.parse(data);
					if (parsedData.topic === 'WORK_EXPERIENCE') {
						if (parsedData.content === '[DONE]' || parsedData.content.includes('[DONE]')) {
							isGenerating.value = false;
							uni.hideLoading();
							uni.showToast({
								title: '生成完成',
								icon: 'success'
							});
							return;
						}
						AIContent.value += parsedData.content;
						return;
					}else if(parsedData.topic === 'INTERN_EXPERIENCE'){
						if (parsedData.content === '[DONE]' || parsedData.content.includes('[DONE]')) {
							isGenerating.value = false;
							uni.hideLoading();
							uni.showToast({
								title: '生成完成',
								icon: 'success'
							});
							return;
						}
						AIContentInternship.value += parsedData.content;
						console.log('AIContentInternship', AIContentInternship.value);
						return;
					}
				} catch (e) {
					// 如果不是JSON格式，直接处理字符串
					if (data === '[DONE]' || data.includes('[DONE]')) {
						isGenerating.value = false;
						uni.hideLoading();
						uni.showToast({
							title: '生成完成',
							icon: 'success'
						});
						return;
					}
					AIContent.value += data;
					AIContentInternship.value += data;
				}
			}
		} catch (error) {
			console.error('处理WebSocket消息出错:', error);
		}
	});

	// 获取列表
	const fetchList = async () => {
		let res
		if (experienceType.value === 'internExperiences') {
			res = await getInternshipExperienceList()
		} else {
			res = await getWorkExperienceList()
		}
		if (res && res.code === 200) {
			workList.value = res.data || []
		}
	}

	// 获取详情
	const fetchDetail = async (id) => {
		let res
		if (experienceType.value === 'internExperiences') {
			res = await getInternshipExperienceDetail(id)
		} else {
			res = await getWorkExperienceDetail(id)
		}
		if (res && res.code === 200) {
			const data = res.data
			formData.companyName = data.companyName
			formData.startDate = data.startDate
			formData.endDate = data.endDate ? data.endDate : '至今'
			if(experienceType.value === 'internExperiences') {
				formData.job = data.internshipJob
				formData.jobDescription = data.internshipDescription
			}else{
				formData.job = data.job
				formData.jobDescription = data.jobDescription
			}
		}
	}

	onLoad(async (options) => {
		if (options.type === 'internExperiences') {
			experienceType.value = 'internExperiences'
			pageTitle.value = '实习经历'
		}
		// await fetchList()
		if (options.index) {
			currentId.value = options.index
			isAdding.value = false
			await fetchDetail(currentId.value)
			// const index = parseInt(options.index)
			// if (!isNaN(index) && index >= 0 && index < workList.value.length) {
			// 	isAdding.value = false
			// 	currentIndex.value = index
			// 	currentId.value = workList.value[index].id
			// 	await fetchDetail(currentId.value)
			// }
		} else {
			isAdding.value = true
			resetForm()
		}
	})

	onMounted(() => {
		const systemInfo = uni.getSystemInfoSync()
		formData.resumeId = resumeStore.resumeId
		statusBarHeight.value = systemInfo.statusBarHeight
		
		// 启动时先尝试连接WebSocket
		try {
			connect().then(() => {
				console.log('WebSocket连接成功，可以接收消息');
			}).catch(err => {
				console.error('WebSocket连接失败:', err);
			});
		} catch (e) {
			console.error('连接WebSocket异常:', e);
		}
	})

	onUnload(() => {
		// 关闭WebSocket连接
		close();
		if (isGenerating.value) {
			isGenerating.value = false;
		}
	})

	const resetForm = () => {
		Object.assign(formData, {
			companyName: '',
			job: '',
			startDate: '',
			endDate: '',
			jobDescription: ''
		})
	}

	const editWork = async (index) => {
		isAdding.value = false
		currentIndex.value = index
		currentId.value = workList.value[index].id
		await fetchDetail(currentId.value)
	}

	const handleStartTimeChange = (e) => {
		formData.startDate = e.detail.value
	}

	const handleEndTimeChange = (e) => {
		formData.endDate = e.detail.value
	}

	const saveWork = async () => {
		if (!formData.companyName.trim()) {
			uni.showToast({
				title: '请输入公司名称',
				icon: 'none'
			})
			return
		}
		if (!formData.job.trim()) {
			uni.showToast({
				title: '请输入职位名称',
				icon: 'none'
			})
			return
		}
		if (!formData.startDate) {
			uni.showToast({
				title: '请选择开始时间',
				icon: 'none'
			})
			return
		}
		if (formData.endDate && formData.startDate > formData.endDate) {
			uni.showToast({
				title: '开始时间不能晚于结束时间',
				icon: 'none'
			})
			return
		}
		const params = {
			// TODO:修改
			// resumeId: '1916784587136589826',
			resumeId:resumeStore.resumeId,
			companyName: formData.companyName,
			startDate: formData.startDate,
			endDate: formData.endDate == '至今' ? '' : formData.endDate,
		}
		if (experienceType.value === 'internExperiences'){
			params.internshipJob = formData.job
			params.internshipDescription = formData.jobDescription
		}else{
			params.job = formData.job
			params.jobDescription = formData.jobDescription
		}
		let res
		if (isAdding.value) {
			res = experienceType.value === 'internExperiences' ?
				await addInternshipExperience(params) :
				await addWorkExperience(params)
		} else {
			params.id = currentId.value
			res = experienceType.value === 'internExperiences' ?
				await updateInternshipExperience(params) :
				await updateWorkExperience(params)
		}
		if (res && res.code === 200) {
			uni.showToast({
				title: isAdding.value ? '添加成功' : '更新成功',
				icon: 'success'
			})
			await fetchList()
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		}
	}

	const confirmDelete = () => {
		deletePopup.value.open()
	}

	const closeDeletePopup = () => {
		deletePopup.value.close()
	}

	const deleteWork = async () => {
		if (currentId.value) {
			let res = experienceType.value === 'internExperiences' ?
				await deleteInternshipExperience(currentId.value) :
				await deleteWorkExperience(currentId.value)
			if (res && res.code === 200) {
				uni.showToast({
					title: '删除成功',
					icon: 'success'
				})
				await fetchList()
				closeDeletePopup()
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			}
		}
	}

	const formatTime = (timeStr) => {
		if (!timeStr) return ''
		return timeStr.replace(/(\d{4})-(\d{2})/, '$1年$2月')
	}

	const formatTimeForPicker = (timeStr) => {
		return timeStr || ''
	}

	// 使用AI生成工作经历
	const generateWork = async () => {
		try {
			// 避免重复请求
			if (isGenerating.value) {
				return;
			}
			
			isGenerating.value = true;
			if(experienceType.value === 'internExperiences'){
				AIContentInternship.value = '';
			}else{
				AIContent.value = '';
			}
			popupWork.value.open();
			
			uni.showLoading({
				title: 'AI生成中...'
			});
			
			// 创建请求数据
			let requestData = {}
			if (experienceType.value === 'internExperiences') {
				requestData = {
					type: 'INTERN_EXPERIENCE',
					aiResumeInternshipExperienceBo: {
						resumeId: resumeStore.resumeId,
						companyName: formData.companyName,
						internshipJob: formData.job,
						startDate: formData.startDate,
						endDate: formData.endDate == '至今' ? '' : formData.endDate,
					}
				}
			}else{
				requestData = {
					type: 'WORK_EXPERIENCE',
					aiResumeWorkExperienceBo: {
						resumeId: resumeStore.resumeId,
						companyName: formData.companyName,
						job: formData.job,
						startDate: formData.startDate,
						endDate: formData.endDate == '至今' ? '' : formData.endDate,
					}
				}
			};
			
			// 检查WebSocket连接状态
			if (!isConnected.value) {
				console.log('WebSocket未连接，尝试连接...');
				await connect();
				console.log('WebSocket连接已建立');
			} else {
				console.log('WebSocket已连接，状态正常');
			}
			
			// 确保WebSocket已连接后，调用HTTP接口触发后端推送消息
			console.log('准备调用HTTP接口触发后端推送...');
			
			// 调用HTTP接口触发后端推送WebSocket消息
			mockInterviewWebSocketProcess(requestData).then(res => {
				// 如果很长时间没收到WebSocket消息，可能后端未正确推送，此时使用HTTP响应结果
				setTimeout(() => {
					if (isGenerating.value && !AIContent.value && experienceType.value === 'workExperiences') {
						console.log('未收到WebSocket消息，使用传统方式');
					}else if(isGenerating.value && !AIContentInternship.value && experienceType.value === 'internExperiences'){
						console.log('未收到WebSocket消息，使用传统方式');
					}
				}, 5000); // 5秒后检查
				
			}).catch(err => {
				console.error('调用HTTP接口失败:', err);
				isGenerating.value = false;
				uni.hideLoading();
				uni.showToast({
					title: '生成失败',
					icon: 'none'
				});
			});
			
		} catch (error) {
			console.error('生成工作经历失败', error);
			isGenerating.value = false;
			uni.hideLoading();
			uni.showToast({
				title: '生成失败',
				icon: 'none'
			});
		}
	}

	// 关闭AI生成弹窗
	const closePopupWork = () => {
		popupWork.value.close();
		isGenerating.value = false;
		uni.hideLoading();
	}

	// 重写AI生成内容
	const rewriteWork = () => {
		isGenerating.value = false;
		setTimeout(() => {
			generateWork();
		}, 300);
	}

	// 替换AI生成内容
	const replaceWork = () => {
		popupWork.value.close();
		if(experienceType.value === 'internExperiences'){
			formData.jobDescription = AIContentInternship.value;
		}else{
			formData.jobDescription = AIContent.value;
		}
		isGenerating.value = false;
	}
</script>

<style lang="scss" scoped>
	.work-experience-page {
		min-height: 100vh;
		background-color: #F8F8F8;

		.content {
			padding: 20px;

			.page-title {
				font-size: 24px;
				font-weight: bold;
				color: #333;
				margin-bottom: 6px;
			}

			.subtitle {
				font-size: 14px;
				color: #999;
				margin-bottom: 24px;
			}
		}

		.experience-list {
			margin-bottom: 20px;

			.experience-item-wrap {
				margin-bottom: 16px;
			}
		}

		.empty-state {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 60px 0;

			.empty-icon {
				width: 140px;
				height: 140px;
				margin-bottom: 16px;
			}

			.empty-text {
				font-size: 15px;
				color: #999;
				text-align: center;
			}
		}

		.add-btn {
			display: flex;
			align-items: center;
			justify-content: center;
			height: 50px;
			background-color: #fff;
			border-radius: 8px;
			margin-top: 16px;

			.add-icon {
				font-size: 20px;
				color: #5ac725;
				margin-right: 6px;
			}

			.add-text {
				font-size: 16px;
				color: #5ac725;
			}
		}

		.form-container {
			background-color: #fff;
			border-radius: 12px 12px 0 0;
			padding-bottom: 20px;

			.form-item {
				margin-bottom: 16px;

				.form-label {
					display: block;
					font-size: 14px;
					color: #333;
					margin-bottom: 8px;

					&.required:after {
						content: '*';
						color: #ff4d4f;
						margin-left: 4px;
					}
				}

				.generate-btn {
					display: inline-block;
					background-color: #f0f7ff;
					color: #4080ff;
					border-radius: 20px;
					font-size: 14px;
					border: none;
					margin: unset;

					.generate-icon {
						margin-right: 4px;
					}
				}

				.form-input,
				.picker-view,
				.time-picker {
					width: 100%;
					height: 44px;
					background-color: #f8f8f8;
					border-radius: 8px;
					padding: 0 12px;
					display: flex;
					align-items: center;
					font-size: 15px;
				}

				.form-input {
					width: unset;
				}

				.form-textarea {
					height: 160px;
					background-color: #f8f8f8;
					border-radius: 8px;
					font-size: 15px;
					padding: 20px;
				}

				.word-count {
					text-align: right;
					font-size: 12px;
					color: #999;
					display: block;
					margin-top: 4px;
				}

				.picker-arrow {
					margin-left: auto;
					font-size: 12px;
					color: #999;
				}

				.time-range {
					display: flex;
					align-items: center;
					justify-content: space-between;
					padding-right: 40rpx;

					.time-picker {
						flex: 1;

						&.disabled {
							opacity: 0.6;
						}
					}

					.time-separator {
						padding: 0 8px;
						color: #666;
					}
				}
			}

			.switch-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
			}

			.form-actions {
				position: fixed;
				bottom: 0;
				left: 0;
				right: 0;
				height: 70px;
				background-color: #fff;
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 0 20px;
				box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);

				.cancel-btn,
				.save-btn {
					flex: 1;
					height: 44px;
					line-height: 44px;
					text-align: center;
					border-radius: 22px;
					font-size: 16px;
				}

				.cancel-btn {
					background-color: #f5f5f5;
					color: #666;
					margin-right: 12px;
				}

				.save-btn {
					background-color: #5ac725;
					color: #fff;
				}
			}

			.delete-action {

				.delete-btn {
					width: 100%;
					height: 44px;
					line-height: 44px;
					text-align: center;
					border-radius: 22px;
					font-size: 16px;
					color: #ff4d4f;
					background-color: #fff;
					border: 1px solid #ff4d4f;
				}
			}
		}

		.bottom {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			height: 70px;
			background-color: #fff;
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 0 20px;
			box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
			z-index: 9;
			gap: 30rpx;
		}

		.action-bar {
			flex: 1;

			.save-btn {
				width: 100%;
				height: 44px;
				line-height: 44px;
				background-color: #5ac725;
				color: #FFFFFF;
				font-size: 16px;
				font-weight: 500;
				border-radius: 22px;
			}
		}
	}
</style>